package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    //根据id批量查询sku
    @Override
    public List<SkuDTO> querySkuListByIds(List<Long> ids) {
        return SkuDTO.convertEntityList(this.listByIds(ids));
    }


    //根据spuID查询sku的集合
    @Override
    public List<SkuDTO> querySkuListBySpuID(Long spuID) {
        return SkuDTO.convertEntityList(this.query().eq("spu_id", spuID).list());
    }



    //商品减库存
    @Override
    @Transactional
    public void subtractStock(Map<Long, Integer> cartsMap) {

//        //定义一个Map来接收多个参数，也可以传入多个参数
//        Map<String, Object> paramHashMap = new HashMap<>();
//
//        //直接减，订单中的商品一个一个减
//        for (Map.Entry<Long, Integer> entry : cartsMap.entrySet()) {
//            Long skuId = entry.getKey();
//            Integer num = entry.getValue();
//            paramHashMap.put("skuId", skuId);
//            paramHashMap.put("num", num);
//            baseMapper.subtractStock(paramHashMap);
//        }

        //批量存储
        executeBatch(sqlSession -> {
            //定义一个Map来接收多个参数，也可以传入多个参数
            Map<String, Object> paramHashMap = new HashMap<>();

            for (Map.Entry<Long, Integer> entry : cartsMap.entrySet()) {
                paramHashMap.put("skuId", entry.getKey());
                paramHashMap.put("num", entry.getValue());

                //执行批量修改 第一个参数：空间名称-->包名+类名+方法名; 第二个参数-->更新sql参数
                sqlSession.update("com.leyou.item.mapper.SkuMapper.subtractStock", paramHashMap);
            }
            //刷新
            sqlSession.flushStatements();
        });


    }


}
